/*
  管理图片资源
*/
class ResourceManager {
  private imageCache: { [key: string]: HTMLImageElement } = {};
  private loadingCount = 0;
  private onLoadComplete: (() => void) | null = null;

  // 预加载单个图片
  preloadImage(key: string, url: string) {
    this.loadingCount++;
    const img = new Image();
    img.onload = () => {
      this.imageCache[key] = img;
      this.loadingCount--;
      if (this.loadingCount === 0 && this.onLoadComplete) {
        this.onLoadComplete();
      }
    };
    img.onerror = () => {
      console.error(`Failed to load image: ${url}`);
      this.loadingCount--;
      if (this.loadingCount === 0 && this.onLoadComplete) {
        this.onLoadComplete();
      }
    };
    img.src = url;
  }

  // 预加载多个图片
  preloadImages(images: { [key: string]: string }) {
    for (const key in images) {
      if (images.hasOwnProperty(key)) {
        this.preloadImage(key, images[key]);
      }
    }
  }

  // 设置加载完成回调
  setOnLoadComplete(callback: () => void) {
    this.onLoadComplete = callback;
  }

  // 获取已加载的图片
  getImage(key: string): HTMLImageElement | undefined {
    return this.imageCache[key];
  }
}

export default ResourceManager;

// const resourceManager = new ResourceManager();
// const imagesToLoad = {
//   'redTile': 'path/to/redTile.png',
//   'blueTile': 'path/to/blueTile.png',
//   // 其他图片
// };

// resourceManager.preloadImages(imagesToLoad);
// resourceManager.setOnLoadComplete(() => {
//   console.log('All images are loaded.');
//   // 在这里开始游戏逻辑
// });
